local p_util = require("libs/playerutil")
local e_util = require("libs/entutil")
local t_util = require "libs/tableutil"


if not IsInMODlist({"隐藏启迪之冠","Concealed Crown","关掉启迪"}) then
    AddPlayerActivatedFunc(function(player)
        local hl = p_util:GetEquip("head")
        if hl and hl.prefab == "alterguardianhat" then
            local c = e_util:GetContainer(hl)
            if c then
                c:Close()
            end
        end
    end)
end


if IsInMODlist("骨盔：去除影怪","Bone Helm","骨头头盔") then return end
-- value:dontshow
local prefabs = {"crawlinghorror","terrorbeak","crawlingnightmare","nightmarebeak"}
local tags = {"monster", "shadow"}
local dontshow
local function func(value)
    dontshow = value
    local ents = e_util:FindEnts(nil, prefabs, 80, tags)
    if value then
        t_util:Pairs(ents, function(_, ent)
            ent:Hide()
        end)
    else
        t_util:Pairs(ents, function(_, ent)
            ent:Show()
        end)
    end
end

t_util:Pairs(prefabs, function(_, prefab)
    AddPrefabPostInit(prefab, function(inst)
        inst:DoPeriodicTask(1, function(inst)
            return dontshow and inst:Hide()
        end)
    end)
end)

local helm_prefab = "skeletonhat"
local ui_bonehelm = require("widgets/hx_bone_helm")
AddClassPostConstruct("widgets/inventorybar",function(self, player)
    local _Rebuild = self.Rebuild
    self.Rebuild = function(...)
        local result = _Rebuild(...)
        
        local head = self.equip and self.equip.head
        if head and head.bgimage then
            local sx = head.bgimage:GetScaledSize()
            if self.ui_bonehelm then self.ui_bonehelm:Kill() end
            local helm = p_util:GetEquip("head")
            self.ui_bonehelm = head:AddChild(ui_bonehelm(sx*1.3, helm and helm.prefab==helm_prefab, dontshow, func))
            self.ui_bonehelm:SetPosition(0, sx*1.5, 0)
            local _OnControl = head.OnControl
            head.OnControl = function(_, ...)
                return self.ui_bonehelm.focus and self.ui_bonehelm:OnControl(...) or _OnControl(_, ...)
            end
        end
        return result
    end
end)
local function isSkeletonhat(meta)
    return meta.item.prefab == helm_prefab
end
local function getUI(player)
    return player and player.HUD and player.HUD.controls and player.HUD.controls.inv and player.HUD.controls.inv.ui_bonehelm
end
local function equip(player, meta)
    if isSkeletonhat(meta) then
        local ui = getUI(player)
        if ui then
            dontshow = false
            ui:Show()
        end
    end
end
local function unequip(player, meta)
    if isSkeletonhat(meta) then
        local ui = getUI(player)
        if ui then
            func()
            ui:Hide()
        end
    end
end

AddPlayerActivatedFunc(function(player)
    player:ListenForEvent("unequip_withhx", unequip)
    player:ListenForEvent("equip_withhx", equip)
end)